﻿Imports System.Data.SqlClient
Imports System.Data.OleDb
Imports System.Web.HttpUtility

Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not String.IsNullOrEmpty(Request.QueryString("added")) Then
            goodMsg.InnerText = "Thank you for adding '" + Request.QueryString("added") + "'"
        End If
        If Not String.IsNullOrEmpty(Request.QueryString("error")) Then
            badMsg.InnerText = Request.QueryString("error")
        End If
        If Not userLoggedIn() Then
            bt_Add.Visible = False
            bt_toShelf.Visible = False
        End If
        search()
    End Sub


    Protected Sub bt_Search_Click(sender As Object, e As EventArgs) Handles bt_Search.Click
        search()

    End Sub

    Protected Sub search()
        Dim bookSearch As String = "SELECT Book.Title, Book.ISBN, Book.year_published AS Published, Book.photo, Author.name AS Author FROM (Book INNER JOIN Author ON Book.author_id = Author.ID) WHERE (Book.Title LIKE '%" + tb_Search.Text + "%')"

        Dim ds As DataSet = GetData(bookSearch)
        Dim dr As DataRow

        Dim tableHTML As String = "<table><thead><tr><th>Cover</th> <th>Title</th> <th>Author</th> <th>Year Published</th> <th>ISBN</th><th>Rating</th></tr></thead><tbody>"



        For Each dr In ds.Tables(0).Rows
            Dim isbn As String = dr("ISBN")
            Dim detailUrl As String = "/details.aspx?b=" + UrlEncode(isbn)

            tableHTML = tableHTML + "<tr><td><a href=""" + detailUrl + """><img width=""200"" src=""/" + dr("photo") + """ ></a></td>"
            tableHTML = tableHTML + "<td><a href=""" + detailUrl + """>" + dr("Title") + "</a></td>"
            tableHTML = tableHTML + "<td>" + dr("Author") + "</td>"
            tableHTML = tableHTML + "<td>" + CStr(dr("Published")) + "</td>"
            tableHTML = tableHTML + "<td>" + dr("ISBN") + "</td>"
            tableHTML = tableHTML + "<td>" + CStr(getAverageRating(isbn)) + "</td></tr>"
        Next
        tableHTML = tableHTML + "</tbody></table>"
        bookTable.InnerHtml = tableHTML


    End Sub

    


    Protected Sub bt_Add_Click(sender As Object, e As EventArgs) Handles bt_Add.Click
        Response.Redirect("addBook.aspx")
    End Sub

    Protected Sub toShelf(sender As Object, e As EventArgs) Handles bt_toShelf.Click
        Response.Redirect("MyBookShelf.aspx")
    End Sub
End Class